package org.example.jnautil.key;

public class LongPressDetectListener extends StatefulKeyListener {
    volatile long pressStartTime;
    volatile boolean isPressing;

    public LongPressDetectListener(int interestKeyCode) {
        super(interestKeyCode);
    }

    @Override
    public ListenKeyResult onKeyEvent(HookKeyHandler hookKeyHandler, boolean isDown) {
        long cur = System.currentTimeMillis();
        if (isDown) {
            if (isPressing) {
                boolean b = cur - pressStartTime > 2000;
                if (b) {
                    return ListenKeyResult.PASS;
                } else {
                    return ListenKeyResult.NOTPASS;
                }
            } else {
                isPressing = true;
                pressStartTime = cur;
                return ListenKeyResult.NOTPASS;
            }
        } else {
            isPressing = false;
            // 如果长按过程中按下了其他按键，弹起长按时就当做这次长按不存在，否则需要重新发送按键消息
            if (hookKeyHandler.lastCode[0] != interestKeyCode) {
                return ListenKeyResult.PASS;
            } else {
                return ListenKeyResult.PASS_AND_UNSTASH;
            }
        }
    }
}
